<template>
  <div class="settings">
    <div class="settings-header">
      <h1>⚙️ 设置</h1>
      <button class="back-btn" @click="goBack">← 返回</button>
    </div>

    <div class="settings-content">
      <!-- 快捷键设置 -->
      <section class="settings-section">
        <h2>⌨️ 快捷键设置</h2>
        <p class="section-description">自定义全局快捷键，在任何时候都能快速截图</p>

        <div class="setting-item">
          <label class="setting-label">
            <span class="label-text">截图快捷键</span>
            <span v-if="hasConflict" class="conflict-warning">⚠️ 快捷键冲突</span>
          </label>
          
          <!-- 预设选择 -->
          <div class="preset-selector">
            <label class="preset-label">快速选择：</label>
            <select 
              class="preset-select"
              :value="shortcuts.screenshot"
              @change="handlePresetChange"
            >
              <option value="">自定义...</option>
              <option 
                v-for="preset in presets" 
                :key="preset.value"
                :value="preset.value"
              >
                {{ preset.label }} - {{ preset.description }}
              </option>
            </select>
          </div>

          <!-- 自定义录制 -->
          <div class="custom-recorder">
            <label class="preset-label">或手动录制：</label>
            <ShortcutRecorder 
              v-model="shortcuts.screenshot"
              @update:modelValue="handleShortcutChange"
            />
          </div>

          <div v-if="conflictMessage" class="conflict-message">
            {{ conflictMessage }}
          </div>
        </div>

        <div class="action-buttons">
          <button 
            class="save-btn"
            :disabled="!hasChanges || hasConflict"
            @click="saveSettings"
          >
            💾 保存设置
          </button>
          <button class="reset-btn" @click="resetToDefault">
            🔄 恢复默认
          </button>
          <button class="test-btn" @click="testShortcut">
            🧪 测试快捷键
          </button>
        </div>

        <div v-if="saveMessage" class="save-message" :class="saveMessageType">
          {{ saveMessage }}
        </div>
      </section>

      <!-- 说明 -->
      <section class="settings-section info-section">
        <h3>💡 说明</h3>
        <ul class="info-list">
          <li>全局快捷键在任何时候都能触发，即使软件在后台运行</li>
          <li>如果快捷键被其他软件占用，会显示冲突警告</li>
          <li>建议选择不常用的组合键，避免与其他软件冲突</li>
          <li>修改后需要点击"保存设置"才会生效</li>
          <li>可以使用"测试快捷键"检查是否能正常触发</li>
        </ul>
      </section>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import ShortcutRecorder from '@/components/Settings/ShortcutRecorder.vue'
import { 
  getShortcuts, 
  saveShortcuts, 
  resetShortcuts,
  convertToElectronFormat,
  SHORTCUT_PRESETS,
  type ShortcutConfig 
} from '@/utils/shortcutManager'

const router = useRouter()

const shortcuts = ref<ShortcutConfig>(getShortcuts())
const originalShortcuts = ref<ShortcutConfig>(getShortcuts())
const hasConflict = ref(false)
const conflictMessage = ref('')
const saveMessage = ref('')
const saveMessageType = ref<'success' | 'error'>('success')
const presets = SHORTCUT_PRESETS

const hasChanges = computed(() => {
  return shortcuts.value.screenshot !== originalShortcuts.value.screenshot
})

// 返回首页
const goBack = async () => {
  if (hasChanges.value) {
    const confirm = window.confirm('有未保存的更改，确定要离开吗？')
    if (!confirm) return
  }
  try {
    await router.push('/')
  } catch (error) {
    console.error('路由跳转失败:', error)
    // 强制刷新
    window.location.hash = '#/'
  }
}

// 预设选择变化
const handlePresetChange = (e: Event) => {
  const value = (e.target as HTMLSelectElement).value
  if (value) {
    shortcuts.value.screenshot = value
    handleShortcutChange(value)
  }
}

// 快捷键变化
const handleShortcutChange = async (newShortcut: string) => {
  if (!newShortcut) {
    hasConflict.value = false
    conflictMessage.value = ''
    return
  }

  // 转换为 Electron 格式
  const electronShortcut = convertToElectronFormat(newShortcut)
  console.log('检测快捷键冲突:', newShortcut, '->', electronShortcut)

  // 通知主进程检测冲突
  if (window.electronAPI?.checkShortcutConflict) {
    try {
      const result = await window.electronAPI.checkShortcutConflict(electronShortcut)
      hasConflict.value = !result.available
      conflictMessage.value = result.available 
        ? '✅ 快捷键可用' 
        : '⚠️ 快捷键已被占用，请选择其他组合'
    } catch (error) {
      console.error('检测快捷键冲突失败:', error)
    }
  }
}

// 保存设置
const saveSettings = async () => {
  if (hasConflict.value) {
    saveMessage.value = '❌ 无法保存：快捷键冲突'
    saveMessageType.value = 'error'
    setTimeout(() => { saveMessage.value = '' }, 3000)
    return
  }

  try {
    // 保存到本地
    saveShortcuts(shortcuts.value)
    originalShortcuts.value = { ...shortcuts.value }

    // 转换为 Electron 格式
    const electronShortcut = convertToElectronFormat(shortcuts.value.screenshot)
    console.log('保存快捷键:', shortcuts.value.screenshot, '->', electronShortcut)

    // 通知主进程更新快捷键
    if (window.electronAPI?.updateShortcut) {
      const result = await window.electronAPI.updateShortcut('screenshot', electronShortcut)
      if (result.success) {
        saveMessage.value = '✅ 设置已保存并生效！'
        saveMessageType.value = 'success'
      } else {
        saveMessage.value = `❌ 保存失败：${result.error}`
        saveMessageType.value = 'error'
      }
    } else {
      saveMessage.value = '✅ 设置已保存！（需要重启应用生效）'
      saveMessageType.value = 'success'
    }

    setTimeout(() => { saveMessage.value = '' }, 3000)
  } catch (error) {
    console.error('保存设置失败:', error)
    saveMessage.value = '❌ 保存失败，请重试'
    saveMessageType.value = 'error'
    setTimeout(() => { saveMessage.value = '' }, 3000)
  }
}

// 恢复默认
const resetToDefault = () => {
  const confirm = window.confirm('确定要恢复默认设置吗？')
  if (!confirm) return

  const defaults = resetShortcuts()
  shortcuts.value = { ...defaults }
  handleShortcutChange(defaults.screenshot)
  
  saveMessage.value = '✅ 已恢复默认设置'
  saveMessageType.value = 'success'
  setTimeout(() => { saveMessage.value = '' }, 3000)
}

// 测试快捷键
const testShortcut = () => {
  alert(`当前快捷键：${shortcuts.value.screenshot}\n\n请尝试按下这个组合键，看是否能触发截图功能。\n\n如果没反应，说明可能被其他软件占用了。`)
}

// 初始化
onMounted(() => {
  handleShortcutChange(shortcuts.value.screenshot)
})
</script>

<style scoped>
.settings {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 40px;
  color: white;
}

.settings-header {
  max-width: 800px;
  margin: 0 auto 40px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.settings-header h1 {
  font-size: 36px;
  margin: 0;
}

.back-btn {
  padding: 10px 20px;
  background-color: rgba(255, 255, 255, 0.2);
  color: white;
  border: 2px solid white;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  transition: all 0.3s ease;
}

.back-btn:hover {
  background-color: rgba(255, 255, 255, 0.3);
  transform: translateX(-5px);
}

.settings-content {
  max-width: 800px;
  margin: 0 auto;
}

.settings-section {
  background-color: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  padding: 32px;
  margin-bottom: 24px;
  color: #333;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.settings-section h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #667eea;
}

.section-description {
  margin: 0 0 24px 0;
  color: #666;
  font-size: 14px;
}

.setting-item {
  margin-bottom: 24px;
}

.setting-label {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  font-weight: 600;
  font-size: 16px;
}

.label-text {
  color: #333;
}

.conflict-warning {
  color: #f44336;
  font-size: 14px;
  animation: blink 1s ease-in-out infinite;
}

@keyframes blink {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

.preset-selector,
.custom-recorder {
  margin-bottom: 16px;
}

.preset-label {
  display: inline-block;
  margin-bottom: 8px;
  font-size: 14px;
  color: #666;
}

.preset-select {
  width: 100%;
  padding: 12px;
  border: 2px solid #ddd;
  border-radius: 8px;
  font-size: 14px;
  background-color: white;
  cursor: pointer;
  transition: border-color 0.3s ease;
}

.preset-select:hover,
.preset-select:focus {
  border-color: #667eea;
  outline: none;
}

.conflict-message {
  margin-top: 8px;
  padding: 8px 12px;
  border-radius: 6px;
  font-size: 14px;
  background-color: #f1f8f4;
  color: #4caf50;
}

.action-buttons {
  display: flex;
  gap: 12px;
  margin-top: 24px;
}

.save-btn,
.reset-btn,
.test-btn {
  padding: 12px 24px;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.save-btn {
  background-color: #4caf50;
  color: white;
  flex: 1;
}

.save-btn:hover:not(:disabled) {
  background-color: #45a049;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(76, 175, 80, 0.3);
}

.save-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
  opacity: 0.6;
}

.reset-btn {
  background-color: #ff9800;
  color: white;
}

.reset-btn:hover {
  background-color: #f57c00;
  transform: translateY(-2px);
}

.test-btn {
  background-color: #2196f3;
  color: white;
}

.test-btn:hover {
  background-color: #1976d2;
  transform: translateY(-2px);
}

.save-message {
  margin-top: 16px;
  padding: 12px;
  border-radius: 8px;
  font-weight: 600;
  text-align: center;
  animation: slideIn 0.3s ease;
}

.save-message.success {
  background-color: #d4edda;
  color: #155724;
}

.save-message.error {
  background-color: #f8d7da;
  color: #721c24;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.info-section h3 {
  margin: 0 0 16px 0;
  font-size: 20px;
  color: #667eea;
}

.info-list {
  margin: 0;
  padding-left: 24px;
  color: #666;
  line-height: 1.8;
}

.info-list li {
  margin-bottom: 8px;
}
</style>

